package com.ayuan.blog.spider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;

/**
 * Created by xiaozhu on 16/6/28.
 */
//@SpringBootApplication
//@EnableAutoConfiguration
//@ComponentScan
//@Component
//@Controller
//@Component
public class BuildProcessor implements PageProcessor{

//    @Qualifier("JobInfoDaoPipeline")
//    @Autowired
    private BuildPipeline buildPipeline;

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    @Override
    public void process(Page page) {
        page.addTargetRequests(page.getHtml().links().regex("http://newhouse.nanjing.fang.com/house/s/jiangning/b\\w+").all());
        Selectable buildNameSelectable = page.getHtml().xpath("//div[@class='nlcd_name']/a[1]/html()");
        List<String> buildNameList = buildNameSelectable.all();
        Selectable buildPriceSelectable = page.getHtml().xpath("//div[@class='nhouse_price']/span/html()");
        List<String> buildPriceList = buildPriceSelectable.all();
        List<Build> buildList = BuildUtil.getBuildList(buildNameList, buildPriceList);
        page.putField("buildList", buildList);
    }

    @Override
    public Site getSite() {
        return site;
    }

//    @RequestMapping("/test")
    public void crawl() {
        Spider.create(new BuildProcessor()).addUrl("http://newhouse.nanjing.fang.com/house/s/jiangning/")
                .addPipeline(buildPipeline).thread(5).run();
    }

    public static void main(String[] args) {
//        Spider.create(new BuildProcessor()).addUrl("http://newhouse.nanjing.fang.com/house/s/jiangning/")
//                .addPipeline(new BuildPipeline("/Users/xiaozhu/Documents/temp/test/build/" + new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").format(new Date()))).thread(5).run();
//        SpringApplication.run(BuildProcessor.class, args);
//        SpringApplication springApplication = new SpringApplication(BuildProcessor.class);
//        springApplication.run(args);
    }
}
